package y23.Oct;

public class Test7 {
    static class TreeNode {
        public int key;
        public TreeNode left;
        public TreeNode right;

        TreeNode(int key) {
            this.key = key;
        }
    }

    public TreeNode root;

    /**
     * 插入一个元素
     *
     * @param key
     */
    public void insert(int key) {
        root = insert(root, key);
    }

    private TreeNode insert(TreeNode root, int key) {
        if (root == null) {
            root = new TreeNode(key);
            return root;
        }

        if (key < root.key) {
            root.left = insert(root.left, key);
        } else if (key > root.key) {
            root.right = insert(root.right, key);
        }
        return root;
    }

    //查找key是否存在
    public TreeNode search(int key) {
        return searchRecursive(root, key);
    }

    private TreeNode searchRecursive(TreeNode root, int key) {
        if (root == null || root.key == key) {
            return root;
        }

        if (key < root.key) {
            return searchRecursive(root.left, key);
        } else {
            return searchRecursive(root.right, key);
        }
    }

    //删除key的值
    public boolean remove(int key) {
        return removeRecursive(root,key)!=null;
    }
    public TreeNode removeRecursive(TreeNode root,int key){
        if (root == null) {
            return null;
        }

        if (key < root.key) {
            root.left = removeRecursive(root.left, key);
        } else if (key > root.key) {
            root.right = removeRecursive(root.right, key);
        } else {
            if (root.left == null) {
                return root.right;
            } else if (root.right == null) {
                return root.left;
            }
            root.key = minimumValue(root.right);
            root.right = removeRecursive(root.right, root.key);
        }
        return root;
    }
    private int minimumValue(TreeNode root) {
        int minimumValue = root.key;
        while (root.left != null) {
            minimumValue = root.left.key;
            root = root.left;
        }
        return minimumValue;
    }
}
